<script setup lang="ts">
import { onMounted, reactive, ref } from "vue"
import { ElMessage, UploadProps, UploadRequestOptions, type FormInstance } from "element-plus"
import jsonData from "#/index.json"

import { updateUserInfoApi, updateWorkExpectationsApi } from "@/api/user/index"
import { type VaildUserInfo } from "@/api/user/types"
import { uploadFile } from "@/api/file"
import { basicDatumFormRules, workExpectationsFormRules } from "./rules"
import { useUserStore } from "@/store/modules/user"

const userStore = useUserStore()
const { basicInfo, gender, roles, workExpectations, getWorkExpectations } = userStore

const activeTab = ref<string>("basicDatum")
const handleSwicthTab = () => {}

// #region 基本资料
const basicDatumFormRef = ref<FormInstance | null>()
const basicDatumFormData = reactive<VaildUserInfo>({
  userName: "",
  userAvatar: "",
  phone: "",
  email: "",
  gender: 0,
  userProfile: ""
})

const handleUploadAvatar = (opts: UploadRequestOptions) => {
  const { file } = opts
  const formData = new FormData()
  formData.append("file", file)
  formData.append("biz", "user_avatar")
  return uploadFile(formData)
}

const handleUploadAvatarSuccess: UploadProps["onSuccess"] = ({ data }) => {
  basicDatumFormData.userAvatar = data
}

const handleInfomationSubmit = () => {
  basicDatumFormRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      updateUserInfoApi(basicDatumFormData).then(() => {
        ElMessage({
          message: "修改个人信息成功",
          type: "success"
        })
      })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

onMounted(() => {
  for (const attr in basicDatumFormData) {
    if (Object.prototype.hasOwnProperty.call(basicDatumFormData, attr)) {
      // @ts-ignore
      basicDatumFormData[attr] = basicInfo[attr]
    }
  }
})
// #endregion

// #region 修改密码

// #endregion

// #region 求职期望
const workExpectationsFormRef = ref()
const workExpectationsForm = reactive({
  studyingExperience: undefined as unknown as number,
  workName: "",
  workPrice: undefined as unknown as number,
  workTime: undefined as unknown as number
})

function handleUpateWorkExpectations() {
  workExpectationsFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    updateWorkExpectationsApi({ ...workExpectationsForm }).then(({ data }) => {
      if (!data) return
      ElMessage({
        message: "修改求职期望成功",
        type: "success"
      })
    })
  })
}

onMounted(async () => {
  await getWorkExpectations()
  Object.keys(workExpectationsForm).forEach((key: string) => {
    delete workExpectationsForm[key as keyof typeof workExpectationsForm]
  })
  Object.assign(workExpectationsForm, JSON.parse(JSON.stringify(workExpectations)))
})
// #endregion
</script>

<template>
  <el-row class="user-info-container" justify="space-around" align="top">
    <el-col :span="7" class="user-info-detail">
      <el-card class="user-info-detail" shadow="always" header="个人信息">
        <el-descriptions :column="1" :label-width="300">
          <el-descriptions-item>
            <img :src="basicInfo.userAvatar" alt="用户头像" width="80" height="80" />
          </el-descriptions-item>
          <el-descriptions-item label="用户名称">{{ basicInfo.userName }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ basicInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ basicInfo.email }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ gender }}</el-descriptions-item>
          <el-descriptions-item label="格言">{{ basicInfo.userProfile }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-col>
    <el-col :span="16" class="user-info-card">
      <el-card class="user-info-card" shadow="always" header="基本资料">
        <el-tabs v-model="activeTab" @tab-click="handleSwicthTab">
          <el-tab-pane label="基本资料" name="basicDatum">
            <el-form
              ref="basicDatumFormRef"
              :model="basicDatumFormData"
              :rules="basicDatumFormRules"
              label-width="80px"
            >
              <el-form-item label="用户名称" prop="userName">
                <el-input v-model.trim="basicDatumFormData.userName" />
              </el-form-item>
              <el-form-item label="用户头像">
                <el-upload
                  action=""
                  accept=".jpg,.jpeg,.png,.gif"
                  :show-file-list="true"
                  :limit="1"
                  :http-request="handleUploadAvatar"
                  :on-success="handleUploadAvatarSuccess"
                >
                  <template v-if="!basicDatumFormData.userAvatar">
                    <el-icon><Plus /></el-icon>
                  </template>
                  <template v-else>
                    <img :src="basicDatumFormData.userAvatar" width="80" height="80" />
                  </template>
                </el-upload>
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model.trim="basicDatumFormData.phone" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model.trim="basicDatumFormData.email" />
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="basicDatumFormData.gender!">
                  <el-radio :value="0" size="large">女</el-radio>
                  <el-radio :value="1" size="large">男</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="个人格言" prop="userProfile">
                <el-input v-model.trim="basicDatumFormData.userProfile" />
              </el-form-item>
              <el-button type="primary" style="margin-left: 80px" @click.prevent="handleInfomationSubmit"
                >提交</el-button
              >
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="changePwd" />
          <el-tab-pane v-if="roles.includes('user')" label="求职期望" name="workExpectations">
            <el-form
              ref="workExpectationsFormRef"
              :model="workExpectationsForm"
              :rules="workExpectationsFormRules"
              inline
              label-width="80px"
            >
              <el-form-item label="学历" prop="studyingExperience">
                <el-select
                  v-model="workExpectationsForm.studyingExperience"
                  placeholder="请选择学历"
                  style="width: 150px"
                >
                  <el-option
                    v-for="{ label, value } in jsonData.studyacademicDegree"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="职位名称" prop="workName">
                <el-input
                  v-model.trim="workExpectationsForm.workName"
                  placeholder="请输入职位名称"
                  style="width: 250px"
                />
              </el-form-item>
              <el-form-item label="期望薪资" prop="workPrice">
                <el-select v-model="workExpectationsForm.workPrice" placeholder="请选择薪资范围" style="width: 150px">
                  <el-option
                    v-for="{ label, value } in jsonData.workPrice"
                    :key="value"
                    :label="label"
                    :value="value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="工作经验" props="workTime">
                <el-select v-model="workExpectationsForm.workTime" style="width: 120px">
                  <el-option v-for="{ label, value } in jsonData.workTime" :key="value" :label="label" :value="value" />
                </el-select>
              </el-form-item>
              <el-button type="primary" @click="handleUpateWorkExpectations" style="margin-left: 80px; display: block"
                >提交</el-button
              >
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.user-info-container {
  padding: 8px 12px;
}
</style>
